import React, { useMemo } from 'react'
import { Avatar, Breadcrumb, Dropdown, Space, Layout, Menu, message } from "antd";
import { Link, useNavigate } from "react-router-dom";
import { HomeOutlined, SmileOutlined } from "@ant-design/icons";
//  引入退出登录的异步action
import { useSelectorAuth, postLogoutAsync } from "@/store/slice/auth";
// 引入dispatch
import { useAppDispatch, useAppTilte } from "@/hooks";
import { renderMenuItem } from '@/router';
const { Header } = Layout;

const IndexHeader = () => {
  const auth = useSelectorAuth();
  // 创建dispatch
  const dispatch = useAppDispatch()
  const navigate = useNavigate();

  // 菜单 暂时静态
  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: (
            <Link to={"/"}>
              返回首页
            </Link>
          ),
          icon: <HomeOutlined />,
        },
        {
          key: '2',
          label: (
            <a onClick={async e => {
              e.preventDefault()
              await dispatch(postLogoutAsync())
              message.success("退出成功");
              navigate("/login");
            }}>退出登陆
            </a>
          ),
          icon: <SmileOutlined />,
        }
      ]}
    />
  );

  /* 
  思路1: 先找一级路由 再找二级路由
  */
  // 找到路由的path
  /* const path = "/"+location.pathname.split("/")[1];
  // 根据路由path找到路由信息
  const info = renderMenuItem().find((v:any)=>v.path === path);
  // 一级标题
  const title = info.label
  console.log(title);
  // 二级标题  从一级路由里面找
  let subTitle
  if(info.children){
    const subInfo =info.children.find((v:any)=> v.path === location.pathname)
    if(subInfo) subTitle = subInfo.label
  } */

  /* 
  思路2 : useMemo
  */
 /*  const titleObj = useMemo(() => {
    const path = '/' + location.pathname.split('/')[1]
    // 根据路由path找到路由信息
    const info = renderMenuItem().find((v: any) => v.path === path);
    // 找到一级标题
    const title = info.label;
    // 找二级标题
    let subTitle;
    if (info.children) {
      const subInfo = info.children.find((v: any) => v.path === location.pathname);
      if (subInfo) subTitle = subInfo.label;
    }return {
      title,
      subTitle
    }
  },[location.pathname]) */

  // 思路：将以下的结果进行封装 hooks->index.ts
  const {title,subTitle} = useAppTilte();






  return (
    <Header className="site-layout-background" style={{ padding: 0 }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
       {/*    思路1和思路3 渲染 */}
         <Breadcrumb.Item>{title} </Breadcrumb.Item>
        <Breadcrumb.Item>{subTitle} </Breadcrumb.Item>
        {/*  思路2 <Breadcrumb.Item>{titleObj.title}</Breadcrumb.Item>
        <Breadcrumb.Item>{titleObj.subTitle}</Breadcrumb.Item> */}
      </Breadcrumb>
      <Space>
        <span>欢迎回来{auth.info.name}!!</span>
        <Dropdown overlay={menu}>
          <a onClick={e => e.preventDefault()}>
            <Avatar src={auth.info.avatar} />
          </a>
        </Dropdown>
      </Space>
    </Header>
  )
}

export default IndexHeader